#include "rfid_api.h"
#include "rfid_app.h"
#include "iso14443a.h"
#include "iso14443b.h"
#include "rfid_board.h"
#include "mifare_api.h"
#include "fm1208_app.h"
#include "rfid_protocol.h"
#include "key_conversion.h"
#include "rfid_detection.h"
#include "real_time_app.h"
#include "device_parameter.h"
#include "network_app.h"
#include "user_wwdg.h"

// #define _TEST_ 1//启动rfid调灵敏度

#if _RFID_FUNCTION_ENABLE_
static uint8_t EmergentFg = 0;
RfidHzDateParameter_t RfidHzDateParameter;
static uint8_t RunStepFlag = 0;
static uint8_t IdentifyType = 3;
/**
 * @brief MIFARE 读卡操作(以梯控的方式读卡)
 *
 * @param CardProtocol         - 卡片协议
 * @return RfidExecuteResult_t - 执行状态
 */
static RfidExecuteResult_t RfidReadMiFareCardElevatorControlProcess(uint8_t CardProtocol);

/**
 * @brief MIFARE 读卡操作(以门锁的方式读卡)
 *
 * @param CardProtocol
 * @return RfidExecuteResult_t
 */
static RfidExecuteResult_t RfidReadMiFareCardDoorLockProcess(uint8_t CardProtocol);

/**
 * @brief FM1208 读卡操作
 *
 * @param CardProtocol         - 卡片协议
 * @return RfidExecuteResult_t - 执行状态
 */
static RfidExecuteResult_t RfidReadCpuCardProcess(uint8_t CardProtocol);

/**
 * @brief 二代身份证读卡操作
 *
 * @return RfidExecuteResult_t - 执行状态
 */
static RfidExecuteResult_t RfidRead2rdGenerationIdCardProcess(void);

/**
 * @brief 卡检测回调
 *
 * @return bool - 捡卡状态（true：触发 false：静默）
 */
static bool RfidCardDetectionCallback(void);

/**
 * @brief 设备自检回调
 *
 */
static void RfidSelfTestCallback(void);

/**
 * @brief 读卡数据回调
 *
 */
static void RfidReadCardDataCallback(void);

/**
 * @brief 读卡数据回调
 *
 */
static void RfidReadCardData2Callback(void);

/**
 * @brief 卡数据更新回调
 *
 */
static void RfidCardDataUpdateCallback(void);

static RfidStatusBit_t RfidStatusBit = {0};

// 梯控读卡
static RfidExecuteResult_t RfidReadMiFareCardElevatorControlProcess(uint8_t CardProtocol)
{
  uint8_t HzReadIndex = 0;
  RfidExecuteResult_t ExecuteResult = CARD_EVENT_PROCESSING;

  switch (RfidStatusBit.SectorParameter.ExecuteStep)
  {
  case CARD_STEP_START:
  {
    uint8_t CardSerialNumber[RFID_NUMBER_OF_CARD_SERIAL_NUMBER] = {0};

    if (RfidSoftwareReset() == true)
    {
      PRINT("[rfid]: reset rfid chip success.\r\n");

      RfidPcdISOType('A');
      RfidSetCW(TX1_TX2_CW_ENABLE);
      RfidDelayMs(RFID_CHIP_REBOOT_WAIT_READY_TIME);

      if (TypeAAuthenticate(CardSerialNumber) == true)
      {
        memcpy(RfidStatusBit.SectorParameter.CardSerialNumber, CardSerialNumber, RFID_NUMBER_OF_MIFARE_CARD_SERIAL_NUMBER);

        if (RfidGetWaitUserActionEn() != true)
        {
          uint8_t SectorKeyValue[RFID_MAX_NUMBER_OF_CODED_TEXT] = {0};
          uint8_t ListNum = 0; // 电梯号，后期须增加

          RfidStatusBit.SectorParameter.RWSectorId = RfidGetElevatorStartSectorNumber();
          RfidGetElevatorSectorAccessKey(SectorKeyValue);
          PRINT("[rfid]: SectorKeyValue:[");
          for (uint8_t i = 0; i < 6; i++)
          {
            PRINT("%02X ", SectorKeyValue[i]);
          }
          PRINT("]\r\n");
          // 计算密钥
          PRINT("RfidStatusBit.SectorParameter.RWSectorId = %d\r\n", RfidStatusBit.SectorParameter.RWSectorId);
          
          CalculatingAccessKeyB(SectorKeyValue, RfidStatusBit.SectorParameter.KeyValueB);
          ElevatorCalculatingAccessKeyA(CardSerialNumber, SectorKeyValue, RfidStatusBit.SectorParameter.KeyValueA, CardProtocol);
          PRINT("[rfid]: verify the user the key: %02X%02X%02X%02X%02X%02X.\r\n", RfidStatusBit.SectorParameter.KeyValueA[0], RfidStatusBit.SectorParameter.KeyValueA[1],
                RfidStatusBit.SectorParameter.KeyValueA[2], RfidStatusBit.SectorParameter.KeyValueA[3], RfidStatusBit.SectorParameter.KeyValueA[4], RfidStatusBit.SectorParameter.KeyValueA[5]);

          PRINT("[rfid]: verify the user the key: %02X%02X%02X%02X%02X%02X.\r\n", RfidStatusBit.SectorParameter.KeyValueA[0], RfidStatusBit.SectorParameter.KeyValueA[1],
                RfidStatusBit.SectorParameter.KeyValueA[2], RfidStatusBit.SectorParameter.KeyValueA[3], RfidStatusBit.SectorParameter.KeyValueA[4], RfidStatusBit.SectorParameter.KeyValueA[5]);

          if (MifareAuthentication(PICC_AUTHENT1A, RfidStatusBit.SectorParameter.RWSectorId * 4, RfidStatusBit.SectorParameter.KeyValueA, RfidStatusBit.SectorParameter.CardSerialNumber) == true)
          { // 校验密钥成功
            PRINT("[rfid] : HzReadIndex = %d\r\n", HzReadIndex);
            for (HzReadIndex = 0; HzReadIndex < 2; HzReadIndex++) // HzReadIndex = 0和1的情况
            {
              if (MifareBlockRead(RfidStatusBit.SectorParameter.RWSectorId * 4 + HzReadIndex, RfidStatusBit.SectorParameter.SectorDataBuff) == true)
              {
                uint8_t i = 0;
                PRINT(" READ HZ BLOCKDATE:");
                for (i = 0; i < 16; i++)
                {
                  PRINT("%02X ", RfidStatusBit.SectorParameter.SectorDataBuff[i]);
                }
                if (HzReadIndex == 0)
                {
                  if ((RfidStatusBit.SectorParameter.SectorDataBuff[0] != 1) || (RfidStatusBit.SectorParameter.SectorDataBuff[1] != 0) ||
                      (RfidStatusBit.SectorParameter.SectorDataBuff[2] != 0) || (RfidStatusBit.SectorParameter.SectorDataBuff[3] != 0))
                  {
                    PRINT("[rfid]: 1failure to read card.\r\n");
                    ExecuteResult = CARD_EXECUTE_ERROR;
                    IdentifyType = 1;
                    return ExecuteResult;
                  }
                }
                ReadHZCardDateHandle(HzReadIndex, RfidStatusBit.SectorParameter.SectorDataBuff, 16);
                memset(RfidStatusBit.SectorParameter.SectorDataBuff, 0x00, 16);
              }
              else
              {
                PRINT("[rfid]: 2failure to read card.\r\n");
                IdentifyType = 1;
                ExecuteResult = CARD_EXECUTE_ERROR;
                HzReadIndex = 0;
                WwdgFeedWatchdog();
                return ExecuteResult; // 只要有一个块读取失败了，直接返回
              }
            }
            if (HzReadIndex == 2)
            {
              uint8_t ReadListAddr = 0;
              // 获取设置的机号
              RfidHzDateParameter.Ele.EleNum = (uint16_t)GetElevatorId();
              ListNum = RfidHzDateParameter.Ele.EleNum;
              PRINT("--------------> ListNum %0d \r\n", ListNum);
              switch (ListNum)
              {
              case 1:
                ReadListAddr = 2;
                break;
              case 2:
                ReadListAddr = 4;
                break;
              case 3:
                ReadListAddr = 5;
                break;
              case 4:
                ReadListAddr = 6;
                break;
              case 5:
                ReadListAddr = 8;
                break;
              case 6:
                ReadListAddr = 9;
                break;
              case 7:
                ReadListAddr = 10;
                break;
              case 8:
                ReadListAddr = 12;
                break;
              default:
                ReadListAddr = 2;
                break;
              }
              if (MifareBlockRead(RfidStatusBit.SectorParameter.RWSectorId * 4 + ReadListAddr, RfidStatusBit.SectorParameter.SectorDataBuff) == true)
              {
                uint8_t i = 0;
                bool result = 0;
                PRINT(" READ BLOCKDATE 2:");
                for (i = 0; i < 16; i++)
                {
                  PRINT("%02X ", RfidStatusBit.SectorParameter.SectorDataBuff[i]);
                }
                PRINT("\r\n");
                result = ReadHZCardDateHandle(2, RfidStatusBit.SectorParameter.SectorDataBuff, 16);
                HzReadIndex = 3;
                if (result == 0)
                {
                  if (IdentifyType == 4)
                  {
                    HzReadIndex = 0;
                    PRINT("[rfid]: card is not in time.\r\n"); // 不在有效期
                    ExecuteResult = CARD_EXECUTE_SUCCESS;

                  }
                  else
                  {
                    HzReadIndex = 0;
                    PRINT("[rfid]: 3failure to read card.\r\n");
                    IdentifyType = 1;
                    ExecuteResult = CARD_EXECUTE_ERROR;
 
                  }
                }
              }
              else
              {
                PRINT("[rfid]: 4failure to read card.\r\n");
                IdentifyType = 1;
                ExecuteResult = CARD_EXECUTE_ERROR;
                HzReadIndex = 0;

              }
            }
            if (HzReadIndex == 3)
            {
              PRINT("[rfid]: read data complete.\r\n");
              IdentifyType = 0;
              ExecuteResult = CARD_EXECUTE_SUCCESS;

            }
          }
          else
          {
            // 读取模式1失败
            PRINT("[rfid] : read step one fail---------\r\n");
            // 执行新任务
            RunStepFlag = 3;
            RFidDelayedStartReadCardData2Task(0);
            ExecuteResult = CARD_IS_RUNNING;
          }
        }
        else
        {
          PRINT("[rfid]: read data complete.\r\n");
          ExecuteResult = CARD_EXECUTE_SUCCESS;
        }
      }
      else
      {
        PRINT("[rfid]: failure to read card, err: CARD_DOES_NOT_EXIST.\r\n");
        ExecuteResult = CARD_DOES_NOT_EXIST;
      }
    }
    else
    {
      PRINT("[rfid]: failure to read card, err: CARD_COMMUNICATION_FAILURE.\r\n");
      ExecuteResult = CARD_COMMUNICATION_FAILURE;
    }
  }
  break;

  default:
  {
    PRINT("[rfid]: failure to read card, err: code run failure.\r\n");
    ExecuteResult = CARD_EXECUTE_ERROR;
  }
  break;
  }

  return ExecuteResult;
}

// 杨格
static RfidExecuteResult_t RfidReadMiFareCardDoorLockProcess(uint8_t CardProtocol)
{
  RfidExecuteResult_t ExecuteResult = CARD_EVENT_PROCESSING;
  PRINT("[rfid] : RfidReadMiFareCardDoorLockProcess.\r\n");

  switch (RfidStatusBit.SectorParameter.ExecuteStep)
  {
  case CARD_STEP_START:
  {
    uint8_t CardSerialNumber[RFID_NUMBER_OF_CARD_SERIAL_NUMBER] = {0};

    if (RfidSoftwareReset() == true)
    {
      PRINT("[rfid]: reset rfid chip success.\r\n");

      RfidPcdISOType('A');
      RfidSetCW(TX1_TX2_CW_ENABLE);
      RfidDelayMs(RFID_CHIP_REBOOT_WAIT_READY_TIME);

      if (TypeAAuthenticate(CardSerialNumber) == true)
      {
        memcpy(RfidStatusBit.SectorParameter.CardSerialNumber, CardSerialNumber, RFID_NUMBER_OF_MIFARE_CARD_SERIAL_NUMBER);

        if (RfidGetWaitUserActionEn() != true)
        {
          uint8_t SectorKeyValue[RFID_MAX_NUMBER_OF_CODED_TEXT] = {0};

          RfidGetSectorAccessKey(SectorKeyValue);
          for (uint8_t i = 0; i < 6; i++)
          {
            PRINT("[rfid]: RfidGetSectorAccessKey.SectorKeyValue[%d] = %02X\r\n", i, SectorKeyValue[i]);
          }
          PRINT("\r\n");
          RfidStatusBit.SectorParameter.RWSectorId = RfidGetStartSectorNumber();
          PRINT("[rfid]: RfidGetSectorAccessKey.RfidStatusBit.SectorParameter.RWSectorId = %d\r\n", RfidStatusBit.SectorParameter.RWSectorId);

          CalculatingAccessKeyB(SectorKeyValue, RfidStatusBit.SectorParameter.KeyValueB);
          DoorLockCalculatingAccessKeyA(CardSerialNumber, SectorKeyValue, RfidStatusBit.SectorParameter.KeyValueA, CardProtocol);
          PRINT("[rfid]: verify the user the key: %02X%02X%02X%02X%02X%02X.\r\n", RfidStatusBit.SectorParameter.KeyValueA[0], RfidStatusBit.SectorParameter.KeyValueA[1],
                RfidStatusBit.SectorParameter.KeyValueA[2], RfidStatusBit.SectorParameter.KeyValueA[3], RfidStatusBit.SectorParameter.KeyValueA[4], RfidStatusBit.SectorParameter.KeyValueA[5]);

          if (MifareAuthentication(PICC_AUTHENT1A, RfidStatusBit.SectorParameter.RWSectorId * 4, RfidStatusBit.SectorParameter.KeyValueA, RfidStatusBit.SectorParameter.CardSerialNumber) == true)
          {
            if (MifareBlockRead(RfidStatusBit.SectorParameter.RWSectorId * 4, RfidStatusBit.SectorParameter.SectorDataBuff) == true)
            {
              RfidStatusBit.SectorParameter.TotalDatLength = RfidGetRWDataLength(RfidStatusBit.SectorParameter.SectorDataBuff);
              if ((RfidStatusBit.SectorParameter.TotalDatLength > 0) && (RfidStatusBit.SectorParameter.TotalDatLength <= RFID_MAX_LENGTH_OF_OPERATION_DATA))
              {;
                RfidStatusBit.SectorParameter.ExecuteStep = CARD_READ_DATA_FROM_SECTOR;
                RFidDelayedStartReadCardData2Task(RFID_CARD_DATA_OPERATION_TIME);
              }
              else
              {
                PRINT("[rfid]: failure to read card, err: CARD_EXECUTE_ERROR, data length: %d.\r\n", RfidStatusBit.SectorParameter.TotalDatLength);
                ExecuteResult = CARD_EXECUTE_ERROR;
              }
            }
            else
            {
              PRINT("[rfid]: failure to read card.\r\n");
              ExecuteResult = CARD_EXECUTE_ERROR;
            }
          }
          else
          {
            PRINT("[rfid]: failure to read card, err: CARD_INSUFFCIENT_AUTHORITY.\r\n");
            ExecuteResult = CARD_INSUFFCIENT_AUTHORITY;
            IdentifyType = CARD_INSUFFCIENT_AUTHORITY;
          }
        }
        else
        {
          PRINT("[rfid]: read data complete.\r\n");
          ExecuteResult = CARD_EXECUTE_SUCCESS;
        }
      }
      else
      {
        PRINT("[rfid]: failure to read card, err: CARD_DOES_NOT_EXIST.\r\n");
        ExecuteResult = CARD_DOES_NOT_EXIST;
      }
    }
    else
    {
      PRINT("[rfid]: failure to read card, err: CARD_COMMUNICATION_FAILURE.\r\n");
      ExecuteResult = CARD_COMMUNICATION_FAILURE;
    }
  }
  break;

  case CARD_STEP_VERIFY_USER_KEY_TO_READ:
  {
    bool VerifyResult = MifareAuthentication(PICC_AUTHENT1A, RfidStatusBit.SectorParameter.RWSectorId * 4, RfidStatusBit.SectorParameter.KeyValueA, RfidStatusBit.SectorParameter.CardSerialNumber);
    if (VerifyResult == true)
    {
      PRINT("[rfid]: verify user Key successfully.\r\n");

      RfidStatusBit.SectorParameter.ExecuteStep = CARD_READ_DATA_FROM_SECTOR;
      RFidDelayedStartReadCardData2Task(RFID_CARD_DATA_OPERATION_TIME);
    }
    else
    {
      PRINT("[rfid]: failure to read card, err: CARD_INSUFFCIENT_AUTHORITY.\r\n");
      ExecuteResult = CARD_INSUFFCIENT_AUTHORITY;
    }
  }
  break;

  case CARD_READ_DATA_FROM_SECTOR:
  {
    PRINT("[rfid] : CARD_READ_DATA_FROM_SECTOR \r\n");
    if (RfidStatusBit.SectorParameter.TotalDatLength > RfidStatusBit.SectorParameter.RWDataSize)
    {
      PRINT("[rfid] : RfidStatusBit.SectorParameter.TotalDatLength = %d\r\n", RfidStatusBit.SectorParameter.TotalDatLength);
      PRINT("[rfid] : RfidStatusBit.SectorParameter.RWSectorId = %d\r\n", RfidStatusBit.SectorParameter.RWSectorId);
      if (MifareBlockRead((RfidStatusBit.SectorParameter.RWSectorId * 4) + RfidStatusBit.SectorParameter.RWBlockId, &RfidStatusBit.SectorParameter.SectorDataBuff[RfidStatusBit.SectorParameter.RWDataSize]) == true)
      {
        RfidStatusBit.SectorParameter.RWDataSize += MIFARE_CARD_BLOCK_DATA_LENGTH;

        RfidStatusBit.SectorParameter.RWBlockId++;
        if (RfidStatusBit.SectorParameter.RWBlockId >= MIFARE_NUMBER_OF_OPERATION_BLOCK_IN_SECTOR)
        {
          RfidStatusBit.SectorParameter.RWBlockId = 0;

          RfidStatusBit.SectorParameter.RWSectorId++;
          RfidStatusBit.SectorParameter.ExecuteStep = CARD_STEP_VERIFY_USER_KEY_TO_READ;
        }

        RFidDelayedStartReadCardData2Task(RFID_CARD_DATA_OPERATION_TIME);
      }
      else
      {
        PRINT("[rfid]: failure to read card.\r\n");
        ExecuteResult = CARD_EXECUTE_ERROR;
      }
    }
    else
    {
      ExecuteResult = CARD_EXECUTE_SUCCESS;

      PRINT("[rfid]: read data complete, length :%d, data: ", RfidStatusBit.SectorParameter.RWDataSize);
      for (uint16_t i = 0; i < RfidStatusBit.SectorParameter.RWDataSize; i++)
        PRINT("%02X", RfidStatusBit.SectorParameter.SectorDataBuff[i]);
      PRINT(".\r\n");
    }
  }
  break;

  default:
  {
    PRINT("[rfid]: failure to read card, err: code run failure.\r\n");
    ExecuteResult = CARD_EXECUTE_ERROR;
  }
  break;
  }

  return ExecuteResult;
}

static RfidExecuteResult_t RfidReadCpuCardProcess(uint8_t CardProtocol)
{
  RfidExecuteResult_t ExecuteResult = CARD_EVENT_PROCESSING;

  switch (RfidStatusBit.SectorParameter.ExecuteStep)
  {
  case CARD_STEP_START:
  {
    if (RfidSoftwareReset() == true)
    {
      PRINT("[rfid]: reset rfid chip success.\r\n");

      RfidPcdISOType('A');
      RfidSetCW(TX1_TX2_CW_ENABLE);
      RfidDelayMs(RFID_CHIP_REBOOT_WAIT_READY_TIME);

      if (TypeAAuthenticate(RfidStatusBit.SectorParameter.CardSerialNumber) == true)
      {
        RfidStatusBit.SectorParameter.ExecuteStep = CARD_STEP_VERIFY_USER_KEY_TO_READ;
        RfidStartReadCardDataTaskNoWait();
      }
      else
      {
        PRINT("[rfid]: failure to read card, err: CARD_DOES_NOT_EXIST.\r\n");
        ExecuteResult = CARD_DOES_NOT_EXIST;
      }
    }
    else
    {
      PRINT("[rfid]: failure to read card, err: CARD_COMMUNICATION_FAILURE.\r\n");
      ExecuteResult = CARD_COMMUNICATION_FAILURE;
    }
  }
  break;

  case CARD_STEP_VERIFY_USER_KEY_TO_READ:
  {
    bool VerifySuccessEn = false;

    if (FmcosRats() == true)
    {
      char *pDirectorName = NULL;

      if (FmcosSelectCardDirector(CPU_CARD_MAIN_DIRECTORY) == true)
      {
        switch (CardProtocol)
        {
        case RFID_CARD_PROTOCOL_HZ:
          pDirectorName = HZ_CPU_USER_DIRECTOR_NAME;
          break;

        default:
          pDirectorName = YG_CPU_USER_DIRECTOR_NAME;
          break;
        }

        if (FmcosEnterDirectoryByFileName(pDirectorName) == true)
        {
          uint8_t Random[4] = {0};

          if (FmcosGetRandomData(4, Random) == true)
          {
            uint8_t EncryptedText[8] = {0}, VerificationKey[8] = {0}, SectorKeyValue[RFID_MAX_NUMBER_OF_CODED_TEXT] = {0};

            memset(EncryptedText, 0, 8);
            memcpy(EncryptedText, Random, 4);

            RfidGetSectorAccessKey(SectorKeyValue);
            DoorLockCalculatingAccessKeyA(RfidStatusBit.SectorParameter.CardSerialNumber, SectorKeyValue, RfidStatusBit.SectorParameter.KeyValueA, CardProtocol);
            RfidCalDesEncrypt(RfidStatusBit.SectorParameter.KeyValueA, EncryptedText, VerificationKey);
            PRINT("[rfid]: verify the user the key: %02X%02X%02X%02X%02X%02X%02X%02X.\r\n", VerificationKey[0], VerificationKey[1], VerificationKey[2],
                  VerificationKey[3], VerificationKey[4], VerificationKey[5], VerificationKey[6], VerificationKey[7]);

            if (FmcosExternalVerification(VerificationKey, 8) == true)
            {
              if (FmcosSelectCardDirector(CPU_BINARY_FILE_DIRECTORY) == true)
              {
                uint16_t ReturnDataSize = 0;
                uint8_t ReturnDataBuff[FM1208_OPERATION_DATA_SIZE] = {0};

                if (FmcosReadBinFile(0, RfidStatusBit.SectorParameter.SectorDataBuff, &ReturnDataSize) == true)
                {
                  RfidStatusBit.SectorParameter.TotalDatLength = RfidGetRWDataLength(RfidStatusBit.SectorParameter.SectorDataBuff);
                  if ((RfidStatusBit.SectorParameter.TotalDatLength > 0) && (RfidStatusBit.SectorParameter.TotalDatLength <= RFID_MAX_LENGTH_OF_OPERATION_DATA))
                  {
                    VerifySuccessEn = true;
                  }
                }
              }
            }
          }
        }
      }
    }

    if (VerifySuccessEn == true)
    {
      PRINT("[rfid]: verify user Key successfully.\r\n");

      RfidStatusBit.SectorParameter.ExecuteStep = CARD_READ_DATA_FROM_SECTOR;
      RfidStartReadCardDataTaskNoWait();
    }
    else
    {
      PRINT("[rfid]: failure to read card, err: CARD_INSUFFCIENT_AUTHORITY.\r\n");
      ExecuteResult = CARD_INSUFFCIENT_AUTHORITY;
    }
  }
  break;

  case CARD_READ_DATA_FROM_SECTOR:
  {
    uint16_t ReturnDataSize = 0;
    uint8_t ReturnDataBuff[FM1208_OPERATION_DATA_SIZE] = {0};

    if (RfidStatusBit.SectorParameter.TotalDatLength > RfidStatusBit.SectorParameter.RWDataSize)
    {
      if (FmcosReadBinFile(RfidStatusBit.SectorParameter.RWDataSize, ReturnDataBuff, &ReturnDataSize) == true)
      {
        uint16_t CopyDataSize = RfidStatusBit.SectorParameter.TotalDatLength - RfidStatusBit.SectorParameter.RWDataSize;
        if (CopyDataSize > FM1208_READ_WRITE_DATA_SIZE)
        {
          CopyDataSize = FM1208_READ_WRITE_DATA_SIZE;
        }

        memcpy(&RfidStatusBit.SectorParameter.SectorDataBuff[RfidStatusBit.SectorParameter.RWDataSize], ReturnDataBuff, CopyDataSize);
        RfidStatusBit.SectorParameter.RWDataSize += CopyDataSize;

        RfidStartReadCardDataTaskNoWait();
      }
      else
      {
        PRINT("[rfid]: failure to read card, err: access sector failure.\r\n");
        ExecuteResult = CARD_EXECUTE_ERROR;
      }
    }
    else
    {
      PRINT("[rfid]: read data complete.\r\n");
      ExecuteResult = CARD_EXECUTE_SUCCESS;
    }
  }
  break;

  default:
  {
    PRINT("[rfid]: failure to read card, err: code run failure.\r\n");
    ExecuteResult = CARD_EXECUTE_ERROR;
  }
  break;
  }

  return ExecuteResult;
}

static RfidExecuteResult_t RfidRead2rdGenerationIdCardProcess(void)
{
  uint8_t ReadCardNumber[64] = {0}, SnrLength = 0;
  RfidExecuteResult_t ExecuteResult = CARD_DOES_NOT_EXIST;

  RfidSoftwareReset();
  RfidPcdISOType('B');
  RfidSetCW(TX1_TX2_CW_ENABLE);
  RfidDelayMs(RFID_CHIP_REBOOT_WAIT_READY_TIME);

  for (uint8_t i = 0; i < 5; i++)
  {
    if (TypeBRequest(ReadCardNumber) == true)
    {
      if (TypeBSelect(ReadCardNumber) == true)
      {
        if (TypeBGetUID(ReadCardNumber, &SnrLength) == true)
        {
          if (SnrLength <= RFID_NUMBER_OF_CARD_SERIAL_NUMBER)
          {
            ExecuteResult = CARD_EXECUTE_SUCCESS;
            memcpy(RfidStatusBit.SectorParameter.CardSerialNumber, ReadCardNumber, RFID_NUMBER_OF_CARD_SERIAL_NUMBER);
          }
        }
      }
    }
  }

  return ExecuteResult;
}

static bool RfidCardDetectionCallback(void)
{
  RfidExitCardDetectionMode();

  PRINT("[rfid]: there's a card approaching.\r\n");

  if (RfidGetDeviceBusyEn() != true)
  {
    if (RfidReportedCardNearby() == true)
    {
      memset(&RfidStatusBit.SectorParameter, 0, sizeof(RfidSectorParameter_t));
      return true;
    }
  }
  else
  {
    memset(&RfidStatusBit.SectorParameter, 0, sizeof(RfidSectorParameter_t));
    RfidStartReadCardDataTaskNoWait();
    return true;
  }

  RfidEnterCardDetectionMode();

  return false;
}

static void RfidSelfTestCallback(void)
{
  bool SelfTestResult = RfidSoftwareReset();
  RfidReportSelfTestResult(SelfTestResult);
#if _TEST_
  RfidSetCW(TX1_TX2_CW_ENABLE);
#endif
}

// 杨格标准协议读卡回调
static void RfidReadCardData2Callback(void)
{
  RfidReadCard_t ReadCardType = RfidGetReaderCardType();
  RfidExecuteResult_t ExecuteResult = CARD_NOT_SUPPORTED;
  uint8_t CardProtocol = (uint8_t)RfidGetCardReadingProtocol();
  uint8_t CardType = RfidGetReadTheCardType();

  PRINT("[rfid] : CardProtocol = %02x\r\n", CardProtocol);

  switch (ReadCardType)
  {
  case MIFARE_CARD_MODE:

    ExecuteResult = RfidReadMiFareCardDoorLockProcess(CardProtocol);
    break;

  case STANDBY_CPU_MODE:
    ExecuteResult = RfidReadCpuCardProcess(CardProtocol);
    break;

  case _2RD_GENERATION_ID_CARD:
    ExecuteResult = RfidRead2rdGenerationIdCardProcess();
    break;
  }
  PRINT("ExecuteResult %0d GetIdentifyType %0d \r\n", ExecuteResult, GetIdentifyType());
  if (ExecuteResult == CARD_IS_RUNNING)
  {
    ExecuteResult = CARD_EXECUTE_SUCCESS;
    return;
  }
  if (ExecuteResult != CARD_EVENT_PROCESSING)
  {
    if (ExecuteResult != CARD_DOES_NOT_EXIST)
    {
      if (RfidGetWaitUserActionEn() == true)
      {
        RfidReportedCardSerialNumber(RfidStatusBit.SectorParameter.CardSerialNumber);
      }
      else
      {
        if (RfidValidateCardDataValidity(RfidStatusBit.SectorParameter.SectorDataBuff, RfidStatusBit.SectorParameter.CardSerialNumber, CardProtocol) != true)
        {
          RfidReportedCardSerialNumber(RfidStatusBit.SectorParameter.CardSerialNumber);
        }
        else
        {
          RfidReportedCardSerialNumber(NULL);
        }
      }
    }
    else
    {
      (RfidGetWaitUserActionEn() == true) ? RfidEnableCardDecetionFunction() : RfidReportedCardSerialNumber(NULL);
    }
  }
  else
  {
    RFidDelayedStartReadCardDataTask(RFID_CARD_DATA_OPERATION_TIME);
  }
}

static void RfidReadCardDataCallback(void)
{
  RfidReadCard_t ReadCardType = RfidGetReaderCardType();
  RfidExecuteResult_t ExecuteResult = CARD_NOT_SUPPORTED;
  uint8_t CardProtocol = (uint8_t)RfidGetCardReadingProtocol();
  uint8_t ThirdPartyCardType = RfidGetThirdPartyTypeOfReading(); // 读取三方识读模式

  switch (ReadCardType)
  {
  case MIFARE_CARD_MODE:
    PRINT("[rfid] : ThirdPartyCardType = %02x, RunStepFlag = %d\r\n", ThirdPartyCardType, RunStepFlag);
    if (ThirdPartyCardType == THIRD_PARTY_READ_TYPE_ELEVATOR_N_DOORLOCK)
    {
      if (RunStepFlag == 0)
      {
        ExecuteResult = RfidReadMiFareCardElevatorControlProcess(CardProtocol);
      }
      else if (RunStepFlag == 3)
      {
        PRINT("[rfid] : RunStepFlag = %d\r\n", RunStepFlag);
        ExecuteResult = RfidReadMiFareCardDoorLockProcess(CardProtocol);
        RunStepFlag = 0;
      }
    }
    else if(ThirdPartyCardType == THIRD_PARTY_READ_TYPE_DOOR_LOCK_SPEI)
    {
      ExecuteResult = RfidReadMiFareCardDoorLockProcess(CardProtocol);
    }else if(ThirdPartyCardType == THIRD_PARTY_READ_TYPE_ELEVATOR_SPECI)
    {
      ExecuteResult = RfidReadMiFareCardElevatorControlProcess(CardProtocol);
    }else{
      ExecuteResult = RfidReadMiFareCardDoorLockProcess(CardProtocol);
    }
    break;

  case STANDBY_CPU_MODE:
    ExecuteResult = RfidReadCpuCardProcess(CardProtocol);
    break;

  case _2RD_GENERATION_ID_CARD:
    ExecuteResult = RfidRead2rdGenerationIdCardProcess();
    break;
  }
  PRINT("ExecuteResult %0d GetIdentifyType %0d \r\n", ExecuteResult, GetIdentifyType());
  if (ExecuteResult == CARD_IS_RUNNING)
  {
    ExecuteResult = CARD_EXECUTE_SUCCESS;
    return;
  }
  if (ExecuteResult != CARD_EVENT_PROCESSING)
  {
    if (ExecuteResult != CARD_DOES_NOT_EXIST)
    {
      if (RfidGetWaitUserActionEn() == true)
      {
        RfidReportedCardSerialNumber(RfidStatusBit.SectorParameter.CardSerialNumber);
      }
      else
      {
        if (RfidValidateCardDataValidity(RfidStatusBit.SectorParameter.SectorDataBuff, RfidStatusBit.SectorParameter.CardSerialNumber, CardProtocol) != true)
        {
          RfidReportedCardSerialNumber(RfidStatusBit.SectorParameter.CardSerialNumber);
        }
        else
        {
          RfidReportedCardSerialNumber(NULL);
        }
      }
    }
    else
    {
      (RfidGetWaitUserActionEn() == true) ? RfidEnableCardDecetionFunction() : RfidReportedCardSerialNumber(NULL);
    }
  }
  else
  {
    RFidDelayedStartReadCardDataTask(RFID_CARD_DATA_OPERATION_TIME);
  }
}

static void RfidCardDataUpdateCallback(void)
{

}
#endif

void RfidEnableCardDecetionFunction(void)
{
#if _TEST_
  
#else
#if _RFID_FUNCTION_ENABLE_
  RfidEnterCardDetectionMode();
#endif
#endif

}

void RfidDisableCardDecetionFunction(void)
{
#if _TEST_
  
#else
#if _RFID_FUNCTION_ENABLE_
  RfidExitCardDetectionMode();
#endif
#endif
}

bool RfidStartDeviceSelfTestTask(void)
{
#if _RFID_FUNCTION_ENABLE_
  RfidStartSelfTestTaskNoWait();
  return true;

#else
  return false;
#endif
}

bool RfidStartReadCardDataTask(void)
{
#if _RFID_FUNCTION_ENABLE_
  RfidStartReadCardDataTaskNoWait();
  return true;

#else
  return false;
#endif
}

bool RfidStartCardDataUpdateTask(void)
{
#if _RFID_FUNCTION_ENABLE_
  RfidStartCardDataUpdateTaskNoWait();
  return true;

#else
  return false;
#endif
}

bool RfidStartLocalRegisterUserTask(void)
{
#if _RFID_FUNCTION_ENABLE_
  if (RfidStatusBit.SystemParameter.BusyEn != true)
  {
    RfidStatusBit.SystemParameter.BusyEn = true;
    memset(&RfidStatusBit.SectorParameter, 0, sizeof(RfidSectorParameter_t));

    RfidPreparationsBeforeLocalRegister();
    return true;
  }
#endif

  return false;
}

void RfidExitCurrectTask(void)
{
#if _RFID_FUNCTION_ENABLE_
  RfidStatusBit.SystemParameter.BusyEn = false;
  memset(&RfidStatusBit.SectorParameter, 0, sizeof(RfidSectorParameter_t));
#endif
}

void RfidConfiguration(void)
{
#if _RFID_FUNCTION_ENABLE_
  RfidExternFunctionTable_t ExternFunctionTable = {0};

  ExternFunctionTable.SelfTestTask = RfidSelfTestCallback;
  ExternFunctionTable.ReadCardDataTask = RfidReadCardDataCallback;
  ExternFunctionTable.ReadCardData2Task = RfidReadCardData2Callback;
  ExternFunctionTable.CardDetectionTask = RfidCardDetectionCallback;
  ExternFunctionTable.CardDataUpdateTask = RfidCardDataUpdateCallback;

  RfidBoardInitialisation(&ExternFunctionTable);

  memset(&RfidStatusBit, 0, sizeof(RfidStatusBit_t));
#endif
}

void Uart_SendOpenEle(uint8_t *iFloor, uint16_t len)
{
}

// 主要功能函数：支持 1~128 位左移 算法
// 将数组整体视为一个 bit 流，左移 shift 位，低位补0
static void shiftAndPrintArray(uint8_t *arr, uint8_t length, uint8_t shift)
{
  if (arr == NULL || length == 0 || shift == 0)
  {
    return;
  }

  // 如果需要左移的位数超过了数组的总位数，则直接清零
  if (shift >= length * 8)
  {
    memset(arr, 0, length);
    return;
  }

  // 计算总共需要左移的字节数和剩余的位数
  uint8_t byteShift = shift / 8;
  uint8_t bitShift = shift % 8;

  // 创建一个新的临时数组来存储结果
  uint8_t temp[length];
  memset(temp, 0, length);

  for (uint8_t i = 0; i < length - byteShift; i++)
  {
    temp[i] = arr[i + byteShift] << bitShift;
    if (bitShift > 0 && i + byteShift + 1 < length)
    {
      temp[i] |= arr[i + byteShift + 1] >> (8 - bitShift);
    }
  }

  // 将结果复制回原数组
  memcpy(arr, temp, length);
}

bool FloorShfitAndPublicFloorCalc(uint8_t StartFloor, uint8_t *PublicFloorDataArray, uint8_t *ResultDataArray)
{
  if (PublicFloorDataArray == NULL || ResultDataArray == NULL)
  {
    PRINT("[rfid_app] : PublicFloorDataArray or ResultDataArray is NULL \r\n");
    return false;
  }
  // PRINT("[rifd_app] : ElectorData.User %0d \r\n", ElectorData.User);

  // 楼层偏移计算
  // uint8_t StartFloor = GetElevatorStartFloor();

  PRINT("[rfid_app]: StartFloor = %d RfidHzDateParameter.Ele.ElePermission before = [", StartFloor);

  for (uint8_t i = 0; i < FLOOR_ARRAY_DATA_LEN; i++)
  {
    PRINT("%02x ", ResultDataArray[i]);
  }
  PRINT("]\r\n");

  // uint8_t PublicFloorData[FLOOR_ARRAY_DATA_LEN] = {0};
  // GetPublicFloorData(PublicFloorData);

  PRINT("[rfid_app]: PublicFloorData before = [\r\n");

  for (uint8_t i = 0; i < FLOOR_ARRAY_DATA_LEN; i++)
  {
    PRINT("%02x ", PublicFloorDataArray[i]);
  }
  PRINT("]\r\n");

  if (StartFloor - 1 > 0)
  { /** 整体偏移StartFloor个bit **/
    shiftAndPrintArray(ResultDataArray, 16, StartFloor - 1);
  }
  PRINT("[rfid_app]: StartFloor = %d RfidHzDateParameter.Ele.ElePermission after = [", StartFloor);
  for (uint8_t i = 0; i < FLOOR_ARRAY_DATA_LEN; i++)
  {
    PRINT("%02x ", ResultDataArray[i]);
  }
  PRINT("]\r\n");

  if (StartFloor - 1 > 0)
  { /** 整体偏移StartFloor个bit **/
    shiftAndPrintArray(PublicFloorDataArray, FLOOR_ARRAY_DATA_LEN, StartFloor - 1);
  }
  PRINT("[rfid_app]: StartFloor = %d PublicFloorData after = [", StartFloor);
  for (uint8_t i = 0; i < FLOOR_ARRAY_DATA_LEN; i++)
  {
    PRINT("%02x ", PublicFloorDataArray[i]);
  }
  PRINT("]\r\n");

  // 楼层合并
  for (uint8_t i = 0; i < FLOOR_ARRAY_DATA_LEN; i++)
  {
    ResultDataArray[i] = ResultDataArray[i] | PublicFloorDataArray[i];
  }
  // 打印最终结果
  PRINT("[rifd_app] : final data: [\r\n");
  for (uint8_t i = 0; i < FLOOR_ARRAY_DATA_LEN; i++)
  {
    PRINT("%02x ", ResultDataArray[i]);
  }
  PRINT("]\r\n");

  return true;
}

static ElectorData_t ElectorData = {0};
extern bool RunningClearCardFunction(uint8_t *CardSerialNumber);
bool ReadHZCardDateHandle(uint8_t Block, uint8_t *iPdate, uint16_t Len)
{
  uint8_t i = 0;
  switch (Block)
  {
  case 0:
    memset(&RfidHzDateParameter, 0, sizeof(RfidHzDateParameter));
    RfidHzDateParameter.Recv_OverFg = 0;
    memcpy(&RfidHzDateParameter.FunctionCode, iPdate, 16);
    break;
  case 1:
    // for(i=0;i<8;i++)
    {
      RfidHzDateParameter.Ele.EleNum = iPdate[i * 2] << 8 | iPdate[i * 2 + 1];
    }
    break;
  case 2:
    memcpy(&RfidHzDateParameter.Ele.ElePermission, iPdate, 16);
    RfidHzDateParameter.Recv_OverFg = 1;
    break;
  default:
    break;
  }
  if (RfidHzDateParameter.Recv_OverFg == 1)
  {
    uint8_t j = 0;
    uint8_t k = 0;
    uint16_t FloorIndex = 0;
    uint8_t Floor_Num[128] = {0};
    uint32_t StartTime = RfidHzDateParameter.StartTime[3] << 24 | RfidHzDateParameter.StartTime[2] << 16 |
                         RfidHzDateParameter.StartTime[1] << 8 | RfidHzDateParameter.StartTime[0];
    uint32_t StopTime = RfidHzDateParameter.StopTime[3] << 24 | RfidHzDateParameter.StopTime[2] << 16 |
                        RfidHzDateParameter.StopTime[1] << 8 | RfidHzDateParameter.StopTime[0];
    uint32_t NowTimestamp = RealTimeMakeCurrentTimestamp();

    uint8_t setresult = 0;
    PRINT("[rifd_app] : StartTime %u StopTime %u \r\n", StartTime, StopTime);
    PRINT("[rifd_app] : USERTPYE %0d \r\n", RfidHzDateParameter.UserType);
    PRINT("[rifd_app] : EmergentFg = %d\r\n", EmergentFg);
    if (RfidHzDateParameter.UserType == EmergencyUser) // 用户类型为3代表紧急卡
    {
      if (EmergentFg)
      {
        Set_EmergenFg(false);
        // Uart_SendOpenEle(RfidHzDateParameter.Ele.ElePermission,16);//发送取消紧急卡开门功能
        NetworkIoBoardOpenEmergencyModeTask(&EmergentFg);
        IdentifyType = 0;
      }
      else
      {
        Set_EmergenFg(true);
        // Uart_SendOpenEle(RfidHzDateParameter.Ele.ElePermission,16);//发送开启紧急卡开门功能
        NetworkIoBoardOpenEmergencyModeTask(&EmergentFg);
        IdentifyType = 0;
      }
      return true;
    }
    else if (RfidHzDateParameter.UserType == ClearData)
    {
      // 清除数据
      PRINT("[rifd_app] : ready to clear all data and restart --->RfidStatusBit.SectorParameter.CardSerialNumber: [\r\n");
      for (uint8_t i = 0; i < 4; i++)
      {
        PRINT("%02x ", RfidStatusBit.SectorParameter.CardSerialNumber[i]);
      }
      PRINT("]\r\n");
      RunningClearCardFunction(RfidStatusBit.SectorParameter.CardSerialNumber);
      return true;
    }

    PRINT("[rifd_app] : GetStartTimeVerifyEn() = %d\r\n", GetStartTimeVerifyEn());
    PRINT("[rifd_app] : StartTime %u StopTime %u NowTimestamp %u\r\n", StartTime, StopTime, NowTimestamp);
    PRINT("[rifd_app] : NowTimestamp %0x\r\n", NowTimestamp);
    {
      ElectorData.User = RfidHzDateParameter.UserType;
      bool PassFlag = false;
      if (GetStartTimeVerifyEn() == false)
      {
        PassFlag = true;
      }
      else
      {
        if (StartTime <= NowTimestamp && NowTimestamp <= StopTime)
        {
          PassFlag = true;
        }
        else
        {
          IdentifyType = 4; // 表示时间验证有问题
          PRINT("[rifd_app] : 9999999\r\n");
          return false;
        }
      }

      if (PassFlag)
      {

        // 楼层偏移计算
        uint8_t StartFloor = GetElevatorStartFloor();

        uint8_t PublicFloorData[FLOOR_ARRAY_DATA_LEN] = {0};
        GetPublicFloorData(PublicFloorData);
        //Davy 0731
        WwdgFeedWatchdog();
        FloorShfitAndPublicFloorCalc(StartFloor, PublicFloorData, RfidHzDateParameter.Ele.ElePermission);

        memcpy(&ElectorData.ElectorFloorData, &RfidHzDateParameter.Ele.ElePermission[0], FLOOR_ARRAY_DATA_LEN);
        // NetworkInitiateOpenSpecificFloorTask(&ElectorData); // 打开指定楼层接口
        // MutiEleBoardComuStatusMechine.MutiEleBoardComuStatus = MUTI_ELE_BOARD_COMU_STATUS_IDLE;
        NetworkMutiEleBoardCommuni(NetworkInitiateOpenSpecificFloorTask, &ElectorData);
        IdentifyType = 0;
        return true;
      }
      else
      {
        return false;
      }
    }
  }
  return true;
}

void Set_EmergenFg(bool iPdate)
{
  EmergentFg = iPdate;
}

bool Get_EmergenFg(void)
{
  return EmergentFg;
}
uint8_t GetIdentifyType(void)
{
  return IdentifyType;
}
